package com.scheduler.config;

import com.scheduler.pojo.Author;
import com.scheduler.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserService implements UserDetailsService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println(username);
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        User user = jdbcTemplate.queryForObject("select * from user where username = " + "'"+username+"'", new BeanPropertyRowMapper<>(User.class));
        Author auhor = jdbcTemplate.queryForObject("select * from  authorities where username = "+"'"+username+"'", new BeanPropertyRowMapper<>(Author.class));
        for (String a:auhor.getAuthority().split(",") ){
            list.add(new SimpleGrantedAuthority(a));
        }

        System.out.println(user.getPassword());
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        return new org.springframework.security.core.userdetails.User(user.getUsername(), encoder.encode(user.getPassword()), list);
    }
}
